package juc.blockqueue.arrayblockqueue;

/**
 * @ClassName RateLimitExample
 * @PackageName juc.blockqueue.arrayblockqueue
 * @projectName myThread
 * @Description TODO
 * @Author games
 * @Date 2025/9/4 上午11:18
 * @Version 1.0
 */
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class RateLimitExample {
    public static void main(String[] args) {
        // 限制并发处理请求数为3
        BlockingQueue<Request> requestQueue = new ArrayBlockingQueue<>(3);

        // 请求生成器
        Thread requestGenerator = new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                Request request = new Request("Request-" + i);
                try {
                    requestQueue.put(request);
                    System.out.println("Request added: " + request.getId());
                    Thread.sleep(200); // 模拟请求间隔
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });

        // 请求处理器（限制同时处理的请求数）
        Thread requestHandler = new Thread(() -> {
            try {
                while (true) {
                    Request request = requestQueue.take();
                    System.out.println("Processing: " + request.getId());
                    // 模拟处理时间
                    Thread.sleep(1000);
                    System.out.println("Completed: " + request.getId());
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        requestGenerator.start();
        requestHandler.start();
    }

    static class Request {
        private final String id;

        public Request(String id) {
            this.id = id;
        }

        public String getId() {
            return id;
        }
    }
}
